var express = require('express');
var moment = require("moment");
var orm = require('orm');
var _ = require('underscore');
var Q = require('q');

var log4js = require('log4js');
var logger = log4js.getLogger();

var router = express.Router();

// 获取首页summery信息
router.get('/summery', function(req, res, next) {
  var dayofweek = moment(Date.now()).day();
  var yesterday = moment().day(dayofweek - 1).format('YYYY-MM-DD');
  logger.info("查询时间：" + yesterday);

  req.models.trade_order_measure_daily.find({
    "create_date": yesterday
  }, function(err, result) {

    if (err) {
      throw err;
    }

    var output = {}
    for (var i = 0; i < result.length; i++) {
      if (result[i].terminal_type == 'TOTAL' && result[i].cps_channel == 'TOTAL') {
        output['orderNum'] = result[i].order_num;
        output['orderPaidNum'] = result[i].paid_order_num;

        output['paidAmount'] = result[i].paid_payment_amount;

        output['pct'] = result[i].pct;
        output['orderCpsNum'] = +(output['orderCpsNum'] || 0) + result[i].paid_order_num
      } else if (result[i].terminal_type == 'TOTAL' && result[i].cps_channel == 'not cps') {
        output['orderCpsNum'] = +(output['orderCpsNum'] || 0) - result[i].paid_order_num
      }
    }

    logger.info("输出数据:" + JSON.stringify({
      result: {
        summery: output
      },
      error: 0
    }));

    res.json({
      result: {
        summery: output
      },
      error: 0
    })
  });
});

var promisqQueryFindAll = function(model, condition) {
  var deferred = Q.defer();

  logger.info(condition)
  model.find(condition).all(function(err, results) {
    if (err) {
      logger.error(err)
      deferred.reject(err);
    } else {
      deferred.resolve(results);
    }
  });

  return deferred.promise;
}

var getEndOfMonth = function (year, month) {
  var map = {
    '01': 31,
    '02': function (year, month) {
      if (year % 4 == 0) {
        return 29
      }else{
        return 28
      }
    },
    '03': 31,
    '04': 30,
    '05': 31,
    '06': 30,
    '07': 31,
    '08': 31,
    '09': 30,
    '10': 31,
    '11': 30,
    '12': 31
  }

  return _.isFunction(map[month]) ? map[month](year, month) : map[month];
}

var queryDailyForMonth = function (models, st) {
  var year = moment(new Date(parseInt(st))).format('YYYY');
  var month = moment(new Date(parseInt(st))).format('MM');
  var endday = getEndOfMonth(year, month);
  return promisqQueryFindAll(models.trade_order_measure_daily, {
    create_date: orm.between(moment().year(year).month(parseInt(month)-1).date(1).format('YYYY-MM-DD'), moment().year(year).month(parseInt(month)-1).date(endday).format('YYYY-MM-DD'))
  });
}

var queryDailyForWeek = function(models, st) {
  return promisqQueryFindAll(models.trade_order_measure_daily, {
    create_date: orm.between(moment(new Date(parseInt(st))).isoWeekday("Monday").format('YYYY-MM-DD'), moment(new Date(parseInt(st))).isoWeekday("Sunday").format('YYYY-MM-DD'))
  });
}

var queryMonth = function (models, st) {
  return promisqQueryFindAll(models.trade_order_measure_monthly, {
    create_month: moment(new Date(parseInt(st))).format('YYYY-MM')
  });
}

var queryWeek = function(models, st) {
  return promisqQueryFindAll(models.trade_order_measure_weekly, {
    week_start: moment(new Date(parseInt(st))).isoWeekday("Monday").format('YYYY-MM-DD'),
    week_end: moment(new Date(parseInt(st))).isoWeekday("Sunday").format('YYYY-MM-DD')
  });
};

var queryDaily = function (models, st) {
  return promisqQueryFindAll(models.trade_order_measure_daily, {
    create_date: moment(new Date(parseInt(st))).format('YYYY-MM-DD')
  });
}

router.get('/chart', function(req, res, next) {

  var period = req.query.period;
  var timestamp = req.query.timestamp || Date.now();
  var map = {
    'day': function (st) {
      Q.all([queryDaily(req.models, st)]).then(function(result) {
        res.json({
          result: {
            summery: result[0],
            detail: null
          },
          error: 0
        });
      }, function() {
        res.json({
          result: null,
          error: -100
        });
      })
    },

    'week': function(st) {

      Q.all([queryDailyForWeek(req.models, st), queryWeek(req.models, st)]).then(function(result) {
        res.json({
          result: {
            summery: result[1],
            detail: result[0]
          },
          error: 0
        });
      }, function() {
        res.json({
          result: null,
          error: -100
        });
      })
    },

    'month': function (st) {
      Q.all([queryDailyForMonth(req.models, st), queryMonth(req.models, st)]).then(function(result) {
        res.json({
          result: {
            summery: result[1],
            detail: result[0]
          },
          error: 0
        });
      }, function() {
        res.json({
          result: null,
          error: -100
        });
      })
    }
  };


  var fn = map[period];

  if (_.isFunction(fn)) {
    fn(timestamp);
  } else {
    res.json({
      result: null,
      error: -100
    });
  }

});

module.exports = router;